<!--  -->
<template>
  <div>

    <div v-if="requestError" class="text-c errorPlace">
      <img width="100px" height="100px" :src="require('@/assets/images/pic_neterror.png')" alt="获取数据失败" />
      <div class="color-b font14" style="margin: 10px 0 0 0">
        获取数据失败!
      </div>
      <van-button plain round size="small" color="#7232dd" type="primary" @click="getdetail">点击重试</van-button>
    </div>


    <van-form v-else @submit="submitFromData" @failed="failedMethod">

      <!-- 头部 -->
      <div class="font15 mt10">
        <div class="pl10">
          <span class="titletext ">{{ params.isDrawup == '1' ? '项目变更起草' : titledata.title }}</span>
        </div>

        <div v-if="params.isDrawup != '1'" class="graytext mt10 font13 pl10">
          <span>工单编号：</span>
          <span class="titletext">{{ titledata.pmInsId }}</span>
        </div>

        <div v-if="params.isDrawup == '1'" class="redtext mt10 mb5 font13 pl10">
          <span>提示：该表单带*字段都为必填项</span>
        </div>

        <div class="bcolor-e" style="height: 8px;"></div>
      </div>


      <van-tabs v-model="active" @change="tabChange" color="#1989fa" sticky animated :lazy-render="false" line-width="33%" offset-top="50">

        <van-tab title="基础信息">
          <tabone ref="toMsgs" :pushParams='params' :fromdata='fromdata' :approveList='approveList'
            :historydata='historydata' />
        </van-tab>

        <van-tab title="其他信息">
          <tabtwo ref="apcTableTwo" :pushParams='params' :fromdata='fromdata' @freshData='freshData($event)' />
        </van-tab>

      </van-tabs>


      <div class="left_botton" v-if="showOpinionMoudle">
        <button block type="button" @click="toMsgValue()" style="color:#60a9ec; display: inline-block;width:100%;border: 0px solid #60a9ec;border-radius: 15px 0px 0px 15px;
          padding:10px 10px 10px 15px;font-size:13px">意见</button>
      </div>


      <div v-if="showNextButton" class="footer">
        <van-button block type="info" native-type="submit" :disabled="!canToNext"
          style="display: inline-block;width:100%;border: 15px solid #60a9ec;">
          {{ toNextValue }}
        </van-button>
      </div>

    </van-form>

  </div>
</template>

<script>
import { getSZTDZJFormDetail, getProjectChangeByPmInsId, getWfLinkTracks, getWfOptMags } from '@/api/dictapi'
import util from "@/assets/js/public";
import tabone from "@/views/apcdetail/tabone"
import tabtwo from "@/views/apcdetail/tabtwo"
import { mapGetters } from "vuex"
import { Notify, Dialog, Toast } from 'vant'
import { ChooseSJ_KEY } from '../../assets/js/dict_process_helper';
import jTool from '../../assets/js/jHelper';

export default {
  name: 'apcdetail',
  data() {
    return {

      active: 0,
      requestError: false,
      params: this.$route.query,
      showHistory: false,
      historydata: {},//已办显示当前办理人

      fromdata: {

        initiator: '',
        initiatorCall: '',
        initiatorTime: '',

        projectName:'',
        projectID: '',
        businessId: '',
        businessName: '',
        

        changeSummaryCode: '',
        changeSummaryName: '',

        milestoneList: [], // 变更后里程碑节点

        linkInfo: [],     // 环节信息
        benefitInfo: [],  // 效益评估

        contractInfo: [], // 合同
      },

      approveList: [],//审批意见列表
      titledata: {}, //主单据信息

      toNextValue: '流转下一步',
      canToNext: true,
      todotype: false,
      toread: false,
    }
  },
  computed: {
    ...mapGetters(['user']),
    ...mapGetters(['userinfo']),

    canChooseSJ() {

      return this.params.isDrawup == '1' || this.params.location == 'dict.start';
    },


    /// 意见
    showOpinionMoudle() {
      return this.params.isDrawup != '1' && this.active == 0;
    },

    showNextButton() {
      return this.todotype || this.toread || this.params.isDrawup == '1';
    }
  },

  created() {

    if (this.params.isDrawup != '1') {

      if (this.params.pmInsType == null && this.params.processType != null) {
        this.params.pmInsType = this.params.processType
      }

      if (this.params.todoType % 2 == 0) {
        this.showHistory = true;
      }

      if (this.params.todoType == '1') {
        this.todotype = true;
      }
      else if (this.params.todoType == '3') {
        this.toread = true;
      }

      this.getdetail();
    }
  },

  //生命周期--创建完成
  activated() {

    if (this.params.isDrawup === '1') {

      let day2 = new Date();
      day2.setTime(day2.getTime());
      let initiatorTime = day2.getFullYear() + "-" + (day2.getMonth() + 1) + "-" + day2.getDate();

      let detailBaseData = {
        initiator: this.userinfo.truename,
        initiatorCall: this.userinfo.preferredMobile,
        initiatorTime: initiatorTime
      }

      Object.assign(this.fromdata, detailBaseData);

      if (this.canChooseSJ) {

        if (localStorage.getItem(ChooseSJ_KEY) != '{}' && 
            localStorage.getItem(ChooseSJ_KEY)) {

          let sjData = JSON.parse(localStorage.getItem(ChooseSJ_KEY));
          localStorage.setItem(ChooseSJ_KEY, '{}')
          sjData.projectID = sjData.projectId;
          Object.assign(this.fromdata, sjData);


          // 表单二 进行网络请求，刷新数据操作
          if (!jTool.stringIsEmpty(this.fromdata.projectID) &&
              !jTool.stringIsEmpty(this.fromdata.businessId)) {

            /// 网络请求 "变更后里程碑节点" "效益评估、环节信息" "合同信息"
            this.$refs.apcTableTwo.requstDrawupInfo()
          }
        }
      }
    }

  },



  //生命周期--挂载完成
  components: {
    tabone,
    tabtwo,
  },

  //方法调用
  methods: {


    failedMethod(data) {

      const errorArr = data.errors;
      const errorObj = errorArr[0];
      const errorMessage = errorObj.message;
      Toast({ type: 'text', message: errorMessage, duration: 1000 });
    },

    tabChange(index) {

      this.active = index;
    },

    toMsgValue() {
      this.$refs.toMsgs.tomsg()
    },
    goBack() {
      this.$router.back(-1) //返回上一页
    },
    onError(result) {
      this.requestError = true;
      Toast.clear();
      Notify(result.message);
    },

    getdetail() {
      Toast.loading({
        message: '加载中',
        forbidClick: false
      });

      getSZTDZJFormDetail(Object.assign(this.params, { userName: this.user.userName }))
        .then((result) => {
          if (!result.data) {
            this.onError(result);
            return;
          }
          if (result.data.data) {
            this.titledata = result.data.data
            this.params.pmInsId = result.data.data.pmInsId;
            this.getProjectChangeByPmInsId();//获取第一步信息
          }

        })
    },
    //获取两个number code
    getProjectChangeByPmInsId() {
      getProjectChangeByPmInsId(this.params)
        .then((result) => {
          Toast.clear();
          if (!result.data) {
            this.onError(result);
            return;
          }
          if (result.data.data) {
            this.fromdata = result.data.data;
          }
          if (this.showHistory == true) {
            this.getWfLinkTracks();
          } else {
            this.getWfOptMags()
          }
        })
    },
    getWfLinkTracks() {
      getWfLinkTracks(Object.assign(this.params), { userName: this.user.userName })
        .then((result) => {
          Toast.clear();
          if (!result.data) {
            Notify(result.message);
            return;
          }
          if (result.data.data) {
            //数据过滤，并生成新的数组
            this.historydata = result.data.data.filter(item => item.CURRENTSTATE == 10)[0]
            if (this.historydata) {
              if (this.historydata.MANAGER) {
                this.showHistory = true;
              } else {
                this.showHistory = false;
              }
            } else {
              this.showHistory = false;
            }
          } else {
            this.showHistory = false;
          }
          this.getWfOptMags()
        })
    },
    getWfOptMags() {
      getWfOptMags(Object.assign(this.params), { userName: this.user.userName })
        .then((result) => {
          if (!result.data) {
            Notify(result.message);
            return;
          }
          this.approveList = result.data.data.reverse();
        })
    },

    submitFromData() {

      //提交流转
      this.controlRule(this.params, this.fromdata.projectID, function () {
        this.onNext();
      });

    },

    // 流转下一步
    onNext() {

      this.params.formData = this.fromdata;
      var formSendData = { "htmlParamMap": {} };
      formSendData.htmlParamMap = this.fromdata;
      formSendData.id = this.titledata.id;
      formSendData.pmInsId = this.titledata.pmInsId;
      formSendData.processType = this.params.pmInsType
      formSendData.workItemId = this.params.workItemId;
      console.log("传给递交页面:", this.params)

      let currentUserCode = util.encrypt(this.user.userName);
      var params1 = {
        kv: {
          currentUserCode: currentUserCode,
          source: 'MOBILE',
          location: this.params.location,
          processInstId: this.params.processInstId,
          processDefName: this.params.processDefName,
          processType: this.params.pmInsType,
          isClaimFun: '3',
          isClaimCounty: '3',
          isOperateCity: '3',
          isOperateCounties: '3',
          isProvinceConfirm: '3',
          isCityConfirm: '3',
        },
        body: {
          location: this.params.location,
          processInstId: this.params.processInstId,
          processDefName: this.params.processDefName,
          source: 'MOBILE',
        }
      };
      var params2 = {
        kv: {
          "currentUserCode": currentUserCode,
          "source": 'MOBILE',
          "location": this.params.location,
          "processInstId": this.params.processInstId,
          'processType': this.params.pmInsType,
          'receiptCode': this.params.processInstId
        },
      };
      var params3 = {
        kv: {
          "source": 'MOBILE',
          "currentUserCode": currentUserCode,
          "workItemId": this.params.todoType == 3 ? "" : this.params.workItemId,
          "processInstId": this.params.processInstId,
          "location": this.params.location,
          "notificationId": this.params.todoType == 3 ? this.params.wfnid : ""
        },
      };
      localStorage.setItem('submitPageParam', JSON.stringify({
        getDecisionsUrl: 'decisionAndUser$api$getDecisions',
        getDecisionsParams: params1,
        getUserUrl: 'decisionAndUser$api$getOrgAndUser',
        getUserParams: params2,
        tosubmintUrl: 'applicationFormProject$api$startSubmitProcess',
        tosubmintParams: params3,
        formData: formSendData,
        fromMoa: this.params.fromMoa,
        type: this.params.todoType == 3 ? "toRead" : "toDo"
      }));
      this.$router.push(
        {
          name: 'srqrsubmit'
        }
      );
    },


    
  }
}
</script>
<style scoped>
.errorPlace {
  position: absolute;
  margin-top: -80px;
  top: 50%;
  margin-left: -50px;
  left: 50%;
}
</style>